package isssr.utility.src;

import isssr.bean.entity.CurrentUser;

import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpSession;

public class AuthorizationListener implements PhaseListener {

	
	public void afterPhase(PhaseEvent event) {

		FacesContext facesContext = event.getFacesContext();
		String currentPage = facesContext.getViewRoot().getViewId();
		
		
		boolean isLoginPage = (currentPage.lastIndexOf("login.xhtml") > -1);
		HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
		
		if(session==null)
		{
			//redirect to login page
			NavigationHandler nh = facesContext.getApplication().getNavigationHandler();
			nh.handleNavigation(facesContext, null, "loginPage");
		}

		else
		{
			CurrentUser cuser = (CurrentUser) FacesContext.getCurrentInstance().
					getExternalContext().getSessionMap().get("currentUser");
			
			if (!isLoginPage && (cuser == null || !cuser.isAuthenticated())) 
			{
				System.out.println("no authenticated");
				NavigationHandler nh = facesContext.getApplication().getNavigationHandler();
				nh.handleNavigation(facesContext, null, "loginPage");
			}
		}
		
	}

	
	public void beforePhase(PhaseEvent event) {}

	
	public PhaseId getPhaseId() {
		return PhaseId.RESTORE_VIEW;
	}
	
}

